<template>
  <el-dialog
    v-model="visible"
    :title="formMode === 'create' ? '新增客户' : '编辑客户'"
    width="600px"
    @close="handleClose"
    class="customer-form-dialog"
  >
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef" 
      label-width="100px"
      class="customer-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入客户名称"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户编码" prop="code">
            <el-input 
              v-model="form.code" 
              placeholder="请输入客户编码"
              :disabled="formMode === 'edit'"
              class="form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户类型" prop="customerType">
            <el-select 
              v-model="form.customerType" 
              placeholder="请选择客户类型"
              style="width: 100%"
              class="form-select"
            >
              <el-option label="企业客户" value="enterprise" />
              <el-option label="个人客户" value="individual" />
              <el-option label="政府客户" value="government" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户等级" prop="customerLevel">
            <el-select 
              v-model="form.customerLevel" 
              placeholder="请选择客户等级"
              style="width: 100%"
              class="form-select"
            >
              <el-option label="VIP客户" value="vip" />
              <el-option label="重要客户" value="important" />
              <el-option label="普通客户" value="normal" />
              <el-option label="潜在客户" value="potential" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户状态" prop="status">
            <el-select 
              v-model="form.status" 
              placeholder="请选择客户状态"
              style="width: 100%"
              class="form-select"
            >
              <el-option label="合作中" value="active" />
              <el-option label="暂停合作" value="suspended" />
              <el-option label="已终止" value="terminated" />
              <el-option label="风险客户" value="risk" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户来源" prop="customerSource">
            <el-select 
              v-model="form.customerSource" 
              placeholder="请选择客户来源"
              style="width: 100%"
              class="form-select"
            >
              <el-option label="政采云" value="政采云" />
              <el-option label="推荐" value="推荐" />
              <el-option label="自主开发" value="自主开发" />
              <el-option label="其他平台" value="其他平台" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-divider>联系信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input 
              v-model="form.contactPerson" 
              placeholder="请输入联系人"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input 
              v-model="form.phone" 
              placeholder="请输入联系电话"
              class="form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="邮箱地址" prop="email">
        <el-input 
          v-model="form.email" 
          placeholder="请输入邮箱地址"
          class="form-input"
        />
      </el-form-item>
      
      <el-divider>业务信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责销售" prop="responsibleSalesman">
            <el-input 
              v-model="form.responsibleSalesman" 
              placeholder="请输入负责销售"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="信用评级" prop="creditRating">
            <el-select 
              v-model="form.creditRating" 
              placeholder="请选择信用评级"
              style="width: 100%"
              class="form-select"
            >
              <el-option label="AAA" value="AAA" />
              <el-option label="AA" value="AA" />
              <el-option label="A" value="A" />
              <el-option label="BBB" value="BBB" />
              <el-option label="BB" value="BB" />
              <el-option label="B" value="B" />
              <el-option label="CCC" value="CCC" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="信用分数" prop="creditScore">
            <el-input-number 
              v-model="form.creditScore" 
              :min="0" 
              :max="100"
              style="width: 100%"
              class="form-input-number"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户价值" prop="customerValue">
            <el-rate
              :model-value="Number(form.customerValue)"
              :max="5"
              allow-half
              style="margin-top: 8px;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注信息"
          class="form-textarea"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitLoading"
          class="submit-btn"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Customer {
  id: string
  name: string
  code: string
  type: string
  level: string
  status: string
  contactPerson: string
  phone: string
  email: string
  customerSource: string
  responsibleSalesman: string
  creditRating: string
  creditScore: number
  customerValue: number
  remark: string
  // 新增字段以匹配后端返回的数据结构
  customerType: string
  customerLevel: string
  contactPersons: string
}

const props = defineProps<{
  modelValue: boolean
  formMode: 'create' | 'edit'
  customerData: Customer | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: Customer): void
  (e: 'close'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = ref<Customer>({
  id: '',
  name: '',
  code: '',
  type: 'enterprise',
  level: 'normal',
  status: 'active',
  contactPerson: '',
  phone: '',
  email: '',
  customerSource: 'self',
  responsibleSalesman: '',
  creditRating: 'A',
  creditScore: 80,
  customerValue: 3,
  remark: '',
  // 新增字段以匹配后端返回的数据结构
  customerType: '',
  customerLevel: '',
  contactPersons: ''
})

// 表单验证规则
const rules = ref<FormRules>({
  name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入客户编码', trigger: 'blur' }
  ],
  customerType: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  customerLevel: [
    { required: true, message: '请选择客户等级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择客户状态', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 监听客户数据变化
watch(() => props.customerData, (newVal: Customer | null) => {
  if (newVal) {
    // 将后端数据映射到表单字段
    form.value = {
      ...newVal,
      // 如果contactPersons是JSON字符串，需要解析并提取第一个联系人的信息
      contactPerson: newVal.contactPersons ? 
        (JSON.parse(newVal.contactPersons)[0]?.name || '') : '',
      phone: newVal.contactPersons ? 
        (JSON.parse(newVal.contactPersons)[0]?.phone || '') : '',
      email: newVal.contactPersons ? 
        (JSON.parse(newVal.contactPersons)[0]?.email || '') : '',
      // 确保客户类型和等级字段正确映射
      customerType: newVal.customerType === '企业客户' ? 'enterprise' : 
                   newVal.customerType === '个人客户' ? 'individual' : 
                   newVal.customerType === '政府客户' ? 'government' : 'enterprise',
      customerLevel: newVal.customerLevel === 'VIP' ? 'vip' : 
                    newVal.customerLevel === '重要' ? 'important' : 
                    newVal.customerLevel === '普通' ? 'normal' : 
                    newVal.customerLevel === '潜在' ? 'potential' : 'normal'
    }
  } else {
    // 重置表单
    form.value = {
      id: '',
      name: '',
      code: '',
      type: 'enterprise',
      level: 'normal',
      status: '1',
      contactPerson: '',
      phone: '',
      email: '',
      customerSource: '自主开发',
      responsibleSalesman: '',
      creditRating: 'A',
      creditScore: 80,
      customerValue: 3,
      remark: '',
      // 新增字段
      customerType: 'enterprise',
      customerLevel: 'normal',
      contactPersons: '[]'
    }
  }
}, { immediate: true })

// 生成客户编码
const generateCustomerCode = () => {
  const prefixMap: Record<string, string> = {
    enterprise: 'ENT',
    individual: 'IND',
    government: 'GOV'
  }
  
  const prefix = prefixMap[form.value.type] || 'CUST'
  const date = new Date()
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `${prefix}${year}${month}${day}${random}`
}

// 监听客户类型变化，自动生成编码
watch(() => form.value.type, (newVal: string) => {
  if (props.formMode === 'create' && !form.value.code) {
    form.value.code = generateCustomerCode()
  }
})

// 方法
const handleClose = () => {
  emit('close')
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 如果是新增客户且没有编码，自动生成
        if (props.formMode === 'create' && !form.value.code) {
          form.value.code = generateCustomerCode()
        }
        
        // 将表单数据转换为后端期望的格式
        const submitData = {
          id: form.value.id,
          name: form.value.name,
          code: form.value.code,
          status: form.value.status === 'active' ? 1 : 0, // 转换为整数
          customerType: form.value.customerType === 'enterprise' ? '企业客户' : 
                       form.value.customerType === 'individual' ? '个人客户' : 
                       form.value.customerType === 'government' ? '政府客户' : '企业客户',
          customerLevel: form.value.customerLevel === 'vip' ? 'VIP' : 
                        form.value.customerLevel === 'important' ? '重要' : 
                        form.value.customerLevel === 'normal' ? '普通' : 
                        form.value.customerLevel === 'potential' ? '潜在' : '普通',
          customerSource: form.value.customerSource,
          responsibleSalesman: form.value.responsibleSalesman,
          creditRating: form.value.creditRating,
          creditScore: form.value.creditScore,
          // 将联系人信息转换为JSON字符串
          contactPersons: JSON.stringify([{
            name: form.value.contactPerson,
            phone: form.value.phone,
            email: form.value.email
          }])
        }
        
        emit('submit', submitData)
        handleClose()
        ElMessage.success(`${props.formMode === 'create' ? '新增' : '编辑'}客户成功`)
      } catch (error) {
        ElMessage.error(`${props.formMode === 'create' ? '新增' : '编辑'}客户失败`)
      } finally {
        submitLoading.value = false
      }
    }
  })
}
</script>

<style scoped>
.customer-form-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.customer-form {
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单元素悬停效果 */
.form-input:hover,
.form-select:hover,
.form-input-number:hover,
.form-textarea:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 取消按钮悬停效果 */
.cancel-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.cancel-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 提交按钮悬停效果 */
.submit-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-form-dialog {
    width: 95% !important;
    margin-top: 20px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .el-col {
    width: 100%;
  }
}
</style>